//
//  UIImageView+YHExtension.swift
//  Adorbee
//
//  Created by amovision on 2024/11/26.
//

import UIKit
#if canImport(SDWebImage)
import SDWebImage
#endif

public extension UIImageView {
  /// 创建`UIImageView`快捷方式
  /// - Parameter name: 自定义名称
  convenience init(named name: String, mode: UIView.ContentMode = .scaleAspectFill) {
    self.init(image: UIImage(named: name))
    self.contentMode = mode
  }
  
  @available(iOS 17.0, *)
  convenience init(resource : ImageResource, mode: UIView.ContentMode = .scaleAspectFill) {
    self.init(image: UIImage(resource: resource))
    self.contentMode = mode
  }

  /// 创建`UIImageView`快捷方式
  /// - Parameter name: 系统名称
  convenience init(snamed name: String) {
    self.init(image: UIImage(systemName: name))
  }

  func yh_setImage(_ url: URL?, placeholder: UIImage? = nil, cacheKey: String? = nil) {
#if canImport(SDWebImage)
    var ctx: [SDWebImageContextOption: Any] = [:]
    if let cacheKey {
      let filter = SDWebImageCacheKeyFilter { _ in
        cacheKey
      }
      ctx[.cacheKeyFilter] = filter
    }
    sd_setImage(with: url, placeholderImage: placeholder, options: [.retryFailed], context: ctx)
#endif
  }

  /// 设置二维码/条形码图片
  /// - Parameters:
  ///   - type: 码类型（二维码/条形码等）
  ///   - string: 要编码的字符串
  ///   - size: 生成图像的尺寸
  ///   - qrColor: 码的颜色
  ///   - bkColor: 背景颜色
  ///   - fadeAnimationDuration: 淡入动画持续时间，0表示无动画
  func setCodeImage(
    type: UIImage.CICodeGeneratorType = .QRCode,
    string: String,
    size: CGSize,
    qrColor: UIColor = .black,
    bkColor: UIColor = .white,
    fadeAnimationDuration: TimeInterval = 0.25
  ) {
    UIImage.createCodeAsync(
      type: type,
      string: string,
      size: size,
      qrColor: qrColor,
      bkColor: bkColor
    ) { [weak self] generatedImage in
      guard let self = self, let image = generatedImage else { return }

      if fadeAnimationDuration > 0 {
        self.alpha = 0
        self.image = image
        UIView.animate(withDuration: fadeAnimationDuration) {
          self.alpha = 1
        }
      } else {
        self.image = image
      }
    }
  }

  var shouldAnimate: Bool {
    get {
       self.isAnimating
    }
    set {
      if newValue {
        self.startAnimating()
      } else {
        self.stopAnimating()
      }
    }
  }
}

public extension UIActivityIndicatorView {
  var shouldAnimate: Bool {
    get {
       self.isAnimating
    }
    set {
      if newValue {
        self.startAnimating()
      } else {
        self.stopAnimating()
      }
    }
  }
}
